<script setup lang="ts">
import { ref, onMounted } from 'vue'
import AddressCard from '../../components/address/AddressCard.vue'
import type { AddressItem } from '../../components/address/AddressCard.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAddressListService, createAddressService, updateAddressService, deleteAddressService, setDefaultAddressService } from '../../api/address'
import { getProvincesService, getCitiesService, getDistrictsService, type RegionItem } from '../../api/region'
const addresses = ref<AddressItem[]>([])

// 拉取地址列表并填充到页面
// 将后端对象映射为前端 AddressItem
const mapServerToItem = (x: any): AddressItem => ({
  id: String(x.id ?? x._id ?? ''),
  name: x.contact,
  province: x.provinceName || x.province,
  city: x.cityName || x.city,
  district: x.districtName || x.district,
  detail: x.detail,
  fullAddress:
    x.fullAddress ||
    x.detail ||
    `${x.provinceName || x.province || ''}${x.cityName || x.city || ''}${x.districtName || x.district || ''} ${x.detail || ''}`.trim(),
  phone: x.phone || x.mobile, // 兼容两种字段名
  isDefault: x.isDefault,
  provinceCode: x.provinceCode || x.province_id || x.province,
  cityCode: x.cityCode || x.city_id || x.city,
  districtCode: x.districtCode || x.district_id || x.district
})

// 拉取地址列表并填充到页面
const fetchList = async () => {
  const res: any = await getAddressListService()
  console.log('获取地址列表响应:', res)
  const list = res?.data || res?.list || []
  console.log('原始地址列表:', list)
  
  // 映射地址数据并排序：默认地址在最顶部
  const mappedAddresses = list.map(mapServerToItem)
  addresses.value = mappedAddresses.sort((a: AddressItem, b: AddressItem) => {
    // 默认地址(isDefault === '1')排在前面，非默认地址(isDefault === '0')按原有顺序排列
    if (a.isDefault === '1' && b.isDefault === '0') return -1
    if (a.isDefault === '0' && b.isDefault === '1') return 1
    return 0
  })
  
  console.log('映射并排序后的地址列表:', addresses.value)
}
onMounted(fetchList)

// 设为默认地址
const setDefault = async (id: string) => {
  try {
    // 先在UI上更新当前地址为默认状态
    const currentAddress = addresses.value.find(addr => addr.id === id)
    if (currentAddress) {
      currentAddress.isDefault = '1'
    }
    
    // 在UI上将其他地址设为非默认
    addresses.value.forEach(addr => {
      if (addr.id !== id && addr.isDefault === '1') {
        addr.isDefault = '0'
      }
    })
    
    // 调用API设置默认地址
    await setDefaultAddressService(id)
    
    // 然后将其他地址设为非默认
    await setOtherAddressesAsNonDefault(id)
    
    ElMessage.success('已设为默认地址')
    
    // 重新获取并排序地址列表，确保默认地址在最顶部
    await fetchList()
  } catch (error) {
    console.error('设置默认地址时出错:', error)
    ElMessage.error('设置默认地址失败')
    // 如果失败，重新获取列表恢复正确状态
    await fetchList()
  }
}

// 将其他地址设为非默认地址
const setOtherAddressesAsNonDefault = async (currentId: string) => {
  try {
    // 遍历所有地址，将非当前地址的其他地址设为非默认
    for (const address of addresses.value) {
      if (address.id !== currentId && address.isDefault === '1') {
        // 调用后端接口将其他地址设为非默认
        await updateAddressService(address.id, { isDefault: '0' })
      }
    }
  } catch (error) {
    console.error('设置其他地址为非默认时出错:', error)
  }
}

// 弹窗与表单
// 弹窗和表单状态
const dialogVisible = ref(false)
const editing = ref(false)
const currentId = ref<string | null>(null)
const formRef = ref()
const form = ref({
  contact: '', phone: '', province: '', city: '', district: '', detail: ''
})

// 表单验证规则
const formRules = {
  contact: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请选择省份', trigger: 'change' }
  ],
  city: [
    { required: true, message: '请选择城市', trigger: 'change' }
  ],
  district: [
    { required: true, message: '请选择区/县', trigger: 'change' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 级联选项
// 级联选项数据
const provinces = ref<RegionItem[]>([])
const cities = ref<RegionItem[]>([])
const districts = ref<RegionItem[]>([])

// 加载省份列表
const loadProvinces = async () => { provinces.value = await getProvincesService() }
const onProvinceChange = async (code: string) => {
  form.value.city = ''
  form.value.district = ''
  cities.value = await getCitiesService(code)
  districts.value = []
}
const onCityChange = async (code: string) => {
  form.value.district = ''
  districts.value = await getDistrictsService(code, form.value.province)
}
onMounted(loadProvinces)

const openEdit = (item: AddressItem | null) => {
  dialogVisible.value = true
  editing.value = !!item
  currentId.value = item?.id || null
  if (item) {
    // console.log('编辑地址项:', item)
    // console.log('手机号字段:', item.phone)
    form.value = {
      contact: item.name,
      phone: item.phone,
      province: item.provinceCode || '',
      city: item.cityCode || '',
      district: item.districtCode || '',
      detail: item.detail || item.fullAddress
    }
    console.log('表单回填后的值:', form.value)
    // 动态回填下拉：先加载城市，再加载区
    if (form.value.province) {
      getCitiesService(form.value.province).then((cs) => {
        cities.value = cs
        if (form.value.city) {
          getDistrictsService(form.value.city, form.value.province).then((ds) => {
            districts.value = ds
          })
        }
      })
    }
  } else {
    // 新增地址时重置表单
    form.value = { 
      contact: '', 
      phone: '', 
      province: '', 
      city: '', 
      district: '', 
      detail: ''
    }
    // 清空级联选项
    cities.value = []
    districts.value = []
  }
}
//编辑
const onEdit = (item: AddressItem) => openEdit(item)
//保存
const onSave = async () => {
  // 表单验证
  try {
    await formRef.value?.validate()
  } catch (error) {
    ElMessage.error('请完善必填信息')
    return
  }
  
  // 统一传过去的参数值为非默认0
  const payload = {
    contact: form.value.contact,
    mobile: form.value.phone,
    province: form.value.province,
    city: form.value.city,
    district: form.value.district,
    detail: form.value.detail,
    isDefault: '0'  // 统一传过去的参数值为非默认0
  }
  
  try {
    if (editing.value && currentId.value) {
      // 编辑地址
      const res: any = await updateAddressService(currentId.value, payload)
      const ok = res?.code === 0 || res?.success === true
      if (ok) {
        ElMessage.success('地址更新成功')
      } else {
        ElMessage.error(res?.message || '地址更新失败')
        return
      }
    } else {
      // 新增地址
      const res: any = await createAddressService(payload)
      const ok = res?.code === 0 || res?.success === true || !!(res?.data || res?.item)
      if (ok) {
        const created = res?.data || res?.item || null
        if (created) {
          // 乐观更新：立即在界面新增卡片
          addresses.value = [mapServerToItem(created), ...addresses.value]
        }
        ElMessage.success('地址添加成功')
      } else {
        ElMessage.error(res?.message || '地址添加失败')
        return
      }
    }
  } catch (e: any) {
    ElMessage.error('请求失败，请稍后重试')
    return
  }
  dialogVisible.value = false
  // 重置表单验证状态
  formRef.value?.clearValidate()
  // 重新拉取列表，确保数据一致性
  await fetchList()
}

const onDelete = async (id: string) => {
  await ElMessageBox.confirm('确认删除该地址吗？', '提示', { type: 'warning' })
  await deleteAddressService(id)
  ElMessage.success('地址已删除')
  await fetchList()
}
</script>
<template>
  <div class="address-page">
    <div class="header">
      <div class="title">我的收货地址</div>
      <el-button type="primary" @click="openEdit(null)">新增收货地址</el-button>
    </div>

    <div class="cards">
      <div v-if="addresses.length === 0" class="empty-holder">没有设置收货地址哦！</div>
      <AddressCard
        v-for="item in addresses"
        :key="item.id"
        :address="item"
        @set-default="setDefault"
        @edit="onEdit"
        @delete="onDelete"
      />
    </div>
    <!-- 编辑/新增弹窗 -->
    <el-dialog v-model="dialogVisible" :title="editing ? '修改收货地址' : '新增收货地址'" width="36rem" append-to-body>
      <div class="edit-form">
        <el-form :model="form" :rules="formRules" ref="formRef" label-width="90px">
          <el-form-item label="收货人：" prop="contact" required>
            <el-input v-model="form.contact" placeholder="请输入收货人姓名" />
          </el-form-item>
          <el-form-item label="手机号：" prop="phone" required>
            <el-input v-model="form.phone" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="所在地区：" required>
            <div class="area-row">
              <el-form-item prop="province" style="margin-bottom: 0;">
                <el-select v-model="form.province" placeholder="请选择省份" @change="onProvinceChange">
                  <el-option v-for="p in provinces" :key="p.code" :label="p.name" :value="p.code" />
                </el-select>
              </el-form-item>
              <el-form-item prop="city" style="margin-bottom: 0;">
                <el-select v-model="form.city" placeholder="请选择城市" @change="onCityChange" :disabled="!form.province">
                  <el-option v-for="c in cities" :key="c.code" :label="c.name" :value="c.code" />
                </el-select>
              </el-form-item>
              <el-form-item prop="district" style="margin-bottom: 0;">
                <el-select v-model="form.district" placeholder="请选择区/县" :disabled="!form.city">
                  <el-option v-for="d in districts" :key="d.code" :label="d.name" :value="d.code" />
                </el-select>
              </el-form-item>
            </div>
          </el-form-item>
          <el-form-item label="详细地址：" prop="detail" required>
            <el-input v-model="form.detail" placeholder="街道、门牌号等详细地址" />
          </el-form-item>
          

        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>



<style scoped lang="scss">
.address-page { padding: 0.75rem 0.75rem 0; }

/* 标题区与分隔线 */
.header {
  display: flex; justify-content: space-between; align-items: center;
  margin-bottom: 0.75rem;
  padding-bottom: 0.5rem;
  border-bottom: 0.0625rem solid #eee;
  .title { font-size: 1.125rem; font-weight: 700; color: #333; }
}

/* 卡片容器由内容撑开 */
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(18rem, 1fr));
  grid-auto-rows: min-content;
  align-content: start;
  gap: 0.75rem;
  align-items: start;
  padding-top: 0.75rem;
}

/* 空状态提示 */
.empty-holder {
  width: 20rem;
  margin: 1rem auto;
  text-align: center;
  color: #999;
}

/* 表单标签与内容布局 */
.edit-form :deep(.el-form-item__label) { font-size: 0.75rem; white-space: nowrap; }
.edit-form :deep(.el-form-item__content) { display: flex; flex-wrap: nowrap; align-items: center; }
.area-row { display: flex; gap: 0.375rem; flex-wrap: nowrap; }
.area-row :deep(.el-select) { width: 6.5rem; }
.edit-form :deep(.el-input__wrapper) { height: 1.875rem; }

/* 表单提示样式 */
.form-tip {
  font-size: 0.75rem;
  color: #909399;
  margin-top: 0.25rem;
  line-height: 1.2;
}

</style>


